<?php

namespace App\Admin\Controllers\Account;

use App\Store\Models\Basic\GoodsCabinetgroup;
use App\Store\Models\Basic\GoodsContent;
use App\Store\Models\Basic\GoodsCraft;
use App\Store\Models\Basic\GoodsMetal;
use App\Store\Models\Basic\GoodsStyle;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Wxapp\Electronicchop;
use App\Store\Models\Wxapp\WxaccountSetting;
use App\Store\Models\Wxapp\WxaccountTemplate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Admin\Models\AdminUser;
use App\Admin\Models\SiteCompany;
use App\Admin\Models\Account;
use App\Admin\Models\SiteStore;
use App\Admin\Validate\Account\Company as ValidateAccountCompany;
use App\Common\Services\Admin\Common as AdminCommon;
use App\Common\Services\CommonExcelExport;
use App\Common\Services\Store\Common;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\AccountMenuRole;
use Illuminate\Support\Facades\DB;

class CompanyController extends Controller
{

    /**
     * 获取公司详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $info = SiteCompany::where(['id' => $id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 获取公司列表
     */
    public function getlist(Request $request)
    {
        $list = SiteCompany::getList($request);

        foreach ($list['list'] as &$val) {
            $val['store_count'] = SiteStore::where(['cp_id' => $val['id'], 'is_del' => 1])->count();
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 新增公司
     */

    public function dopostadd(Request $request)
    {
        $req_data = $request->only([
            'p_code', 'c_code', 'd_code', 'address_area', 'company_name', 'contact_name', 'contact_phone',
            'account_name', 'is_training', 'is_open_sms', 'is_finance', 'mchid', 'appid', 'appkey', 'signname'
        ]);

        $Validate = new ValidateAccountCompany;
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $req_data['is_open_sms'] = isset($req_data['is_open_sms']) ? intval($req_data['is_open_sms']) : 1;
        if (in_array($req_data['is_open_sms'], [1, 2])) {
            if ($req_data['is_open_sms'] == 2) {
                if (!isset($req_data['mchid']) || $req_data['mchid'] == '' || !isset($req_data['appid']) || $req_data['appid'] == '' || !isset($req_data['appkey']) || $req_data['appkey'] == '') {
                    return response()->json(['code' => '001', 'msg' => '开通短信时，请保持短信参数完整']);
                }
            }
        } else {
            return response()->json(['code' => '001', 'msg' => '是否开通短信参数错误']);
        }

//        $isexist = SiteCompany::where([['company_name', $req_data['company_name']],['is_del',1]])->first();
//        if ($isexist) {
//            return response()->json(['code' => '001', 'msg' => '公司名称不允许重复']);
//        }

        //判断账号是否重复
        $isexist = Account::where([['account_name', $req_data['account_name']], ['is_del', 1]])->first();
        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '账号不允许重复']);
        }

        $isexist = AdminUser::where([['username', $req_data['account_name']], ['type', 1]])->first();
        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '账号信息不可与超管信息相同']);
        }

        $data = $req_data;
        $data['create_at'] = time();
        $data['update_at'] = time();
        $data['training_min'] = !empty($req_data['training_min']) ? $req_data['training_min'] : 0;
        $data['training_max'] = !empty($req_data['training_max']) ? $req_data['training_max'] : 0;
        $data['audit_status'] = 2; //提交成功直接提交审核
        $data['admin_user_id'] = AdminCommon::getCurrentAdminId($request);


        DB::beginTransaction();
        try {

            $cp_id = SiteCompany::create($data)->id;
            $account = Account::create(['type' => 9, 'cp_id' => $cp_id, 'account_name' => $req_data['account_name'], 'real_name' => $req_data['contact_name'], 'mobile' => $req_data['contact_phone'], 'password' => MD5(MD5('zhuxiaobao_' . env('ACCOUNT_DEF_PWD'))), 'create_at' => time(), 'update_at' => time(), 'is_show_manger' => 1, 'is_super' => 1]);

            //新增默认电子章
            $data = ['imgpath' => env('ALI_OSS_URL') . 'upload/202410/0b5ff6906e9fcd39779dff6b515d3fad.png', 'cp_id' => $cp_id, 'status' => 2];
            $data['create_at'] = time();
            $data['update_at'] = time();
            Electronicchop::create($data);
            $msg = '';
            AccountMenuRole::setAccountRole(0, 9);

            $default['cp_id'] = $cp_id;
            $default['account_id'] = $account->id;
            $default['account_name'] = $req_data['account_name'];
            $this->addDefaultData($default);

            DB::commit();
            return response()->json(['code' => '000', 'msg' => '新增公司成功']);

        } catch (\Exception $e) {
            DB::rollBack();
            info('新增公司失败' . $e->getMessage() . $e->getLine());
            return response()->json(['code' => '001', 'msg' => '新增公司失败' . $e->getMessage()]);
        }


    }

    /**
     * 编辑公司
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only([
            'id', 'p_code', 'c_code', 'd_code', 'address_area', 'company_name', 'contact_name', 'contact_phone',
            'is_training', 'is_finance', 'is_open_sms', 'mchid', 'appid', 'appkey', 'signname'
        ]);

        $Validate = new ValidateAccountCompany('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $req_data['is_open_sms'] = isset($req_data['is_open_sms']) ? intval($req_data['is_open_sms']) : 1;
        if (in_array($req_data['is_open_sms'], [1, 2])) {
            if ($req_data['is_open_sms'] == 2) {
                if (!isset($req_data['mchid']) || $req_data['mchid'] == '' || !isset($req_data['appid']) || $req_data['appid'] == '' || !isset($req_data['appkey']) || $req_data['appkey'] == '') {
                    return response()->json(['code' => '001', 'msg' => '开通短信时，请保持短信参数完整']);
                }
            }
        } else {
            return response()->json(['code' => '001', 'msg' => '是否开通短信参数错误']);
        }

        $info = SiteCompany::where([['id', $req_data['id']], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '公司参数错误']);
        }

//        $isexist = SiteCompany::where([['company_name', $req_data['company_name']], ['id', '<>', $req_data['id']],['is_del',1]])->first();
//        if ($isexist) {
//            return response()->json(['code' => '001', 'msg' => '公司名称不允许重复']);
//        }
        $data = $req_data;
        unset($data['id']);
        $data['update_at'] = time();
        if (isset($data['audit_status']) && $data['audit_status'] != 3) {
            $data['audit_status'] = 2;
        }

        //修改名字和账号
        Account::query()
            ->where([
                'type' => 9,
                'is_del' => 1,
                'cp_id' => $req_data['id'],
                'is_super' => 1
            ])
            ->update([
                'real_name' => $req_data['contact_name'],
                'mobile' => $req_data['contact_phone'],
                'update_at' => time()
            ]);

        SiteCompany::where(['id' => $req_data['id']])->update($data);

        return response()->json(['code' => '000', 'msg' => '编辑公司成功']);
    }


    /**
     * 重置密码
     */
    public function resetpassword(Request $request)
    {
        //重置后需重置账号登陆状态
        $id = $request->id ?? 0;
        $info = SiteCompany::where([['id', $id], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = Account::where(['type' => 9, 'cp_id' => $id, 'is_super' => 1])->first();
        if (!$accountinfo) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $password = MD5(MD5('zhuxiaobao_' . env('ACCOUNT_DEF_PWD')));
        Account::where([['id', $accountinfo->id], ['is_super', 1]])->update(['password' => $password, 'update_at' => time()]);

        //重置后需重置账号登陆状态
        Common::cleartokenkey($accountinfo->id);
        Common::cleartokenkeybywxapp($accountinfo->id);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 审核成功
     */
    public function doauditsuccess(Request $request)
    {
        $id = $request->id ?? 0;
        $info = SiteCompany::where([['id', $id], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 2) {
            return response()->json(['code' => '001', 'msg' => '公司信息状态未处于待审核']);
        }
        SiteCompany::where([['id', $id]])->update(['audit_status' => 3, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 审核取消--失败重新编辑
     */
    public function doauditcancel(Request $request)
    {
        $id = $request->id ?? 0;
        $info = SiteCompany::where([['id', $id], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 2) {
            return response()->json(['code' => '001', 'msg' => '公司信息状态未处于待审核']);
        }
        SiteCompany::where([['id', $id]])->update(['audit_status' => 4, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    { //isgetall=1;
        $list = SiteCompany::getList($request)['list'];
        $exceldata = [];
        $row = [
            ['company_name' => '用户公司列表'],
            [
                'company_name' => '公司名称',
                'address_area' => '归属区域',
                'contact_name' => '负责人姓名',
                'contact_phone' => '联系电话',
                'create_at' => '创建时间',
                'update_at' => '修改时间',
                'audit_status' => '审核状态',
                'account_name' => '账号',
            ]
        ];
        foreach ($list as $val) {
            $exceldata[] = [
                'company_name' => $val['company_name'],
                'address_area' => $val['address_area'],
                'contact_name' => $val['contact_name'],
                'contact_phone' => $val['contact_phone'],
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'update_at' => date('Y-m-d H:i:s', $val['update_at']),
                'audit_status' => $val['audit_status'] == 2 ? '审核中' : ($val['audit_status'] == 3 ? '审核成功' : '审核取消'),
                'account_name' => $val['account_name'],
            ];
        }

        $filename = '公司信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }


    public function dodel(Request $request)
    {
        $id = $request->id ?? 0;
        $info = SiteCompany::where([['id', $id], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountlist = Account::where(['cp_id' => $id])->get()->toArray();
        DB::beginTransaction();
        try {
            SiteCompany::where([['id', $id]])->update(['is_del' => 2, 'del_at' => time()]);
            SiteStore::where(['cp_id' => $id])->update(['is_del' => 2, 'del_at' => time()]);
            GoodsCabinetgroup::query()
                ->where(['cp_id' => $id])
                ->update(['is_del' => 2, 'del_at' => time()]);
            GoodsCraft::query()
                ->where(['cp_id' => $id])
                ->update(['is_del' => 2, 'del_at' => time()]);

            GoodsStyle::query()
                ->where(['cp_id' => $id])
                ->update(['is_del' => 2, 'del_at' => time()]);

            GoodsMetal::query()
                ->where(['cp_id' => $id])
                ->update(['is_del' => 2, 'del_at' => time()]);

            PaytypeList::query()
                ->where(['cp_id' => $id])
                ->update(['is_del' => 2, 'del_at' => time()]);

            GoodsContent::query()
                ->where(['cp_id' => $id])
                ->update(['is_del' => 2, 'del_at' => time()]);

            foreach ($accountlist as $val) {
                Account::where(['id' => $val['id']])->update(['is_del' => 2, 'del_at' => time()]);
                Common::cleartokenkey($val['id']);
                Common::cleartokenkeybywxapp($val['id']);
            }


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '操作失败']);
        }


        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 写入默认数据
     * @param $params
     * @return true
     */
    public function addDefaultData($params)
    {
        $cabinetgroup = ['足金柜', 'K金柜', '钻石柜', '银饰柜', '玉器柜', '铂金柜', '彩宝柜', '钯金柜', '手表柜', '其他'];
        $cabinetData = [];
        foreach ($cabinetgroup as $cabinet) {
            $cabinetData[] = [
                'cp_id' => $params['cp_id'],
                'cabinetgroup_name' => $cabinet,
                'create_account_id' => $params['account_id'],
                'create_account_real_name' => $params['account_name'],
                'create_at' => time()
            ];
        }

        GoodsCabinetgroup::query()->insert($cabinetData);

        $craftArr = ['3D工艺', '5D工艺', '5G工艺', '古法工艺', '珐琅彩', '精品工艺'];
        $craftData = [];
        foreach ($craftArr as $craft) {
            $craftData[] = [
                'cp_id' => $params['cp_id'],
                'craft_name' => $craft,
                'create_account_id' => $params['account_id'],
                'create_account_real_name' => $params['account_name'],
                'create_at' => time()
            ];
        }
        GoodsCraft::query()->insert($craftData);

        $styleArr = ['戒指', '项链', '挂坠', '手链', '摆件', '手镯', '耳饰', '金条', '手表', '套链', '手串'];
        $styleData = [];
        foreach ($styleArr as $style) {
            $styleData[] = [
                'cp_id' => $params['cp_id'],
                'style_name' => $style,
                'create_account_id' => $params['account_id'],
                'create_account_real_name' => $params['account_name'],
                'create_at' => time()
            ];
        }
        GoodsStyle::query()->insert($styleData);


        $metalArr = ['足金', '足银', '银925', '金750', '金916', '铂950', '铂990','其他'];
        $metalData = [];
        foreach ($metalArr as $metal) {
            $metalData[] = [
                'cp_id' => $params['cp_id'],
                'metal_name' => $metal,
                'create_account_id' => $params['account_id'],
                'create_account_real_name' => $params['account_name'],
                'create_at' => time()
            ];
        }

        GoodsMetal::query()->insert($metalData);

        // 默认写支付方式
        $payArr = ['支付宝', '微信', '现金', '银行卡', '储值卡'];
        $payData = [];
        foreach ($payArr as $pay) {
            $payData[] = [
                'cp_id' => $params['cp_id'],
                'paytype_name' => $pay,
                'create_account_id' => $params['account_id'],
                'create_account_real_name' => $params['account_name'],
                'create_at' => time()
            ];
        }
        PaytypeList::query()->insert($payData);


        // 默认写含量数据

        $contentArr = ['999‰', '999.9‰', '999.99‰', '990‰', '925‰', '750‰', '916‰', '950‰'];
        $contentData = [];
        foreach ($contentArr as $content) {
            $contentData[] = [
                'cp_id' => $params['cp_id'],
                'content_name' => $content,
                'create_account_id' => $params['account_id'],
                'create_account_real_name' => $params['account_name'],
                'create_at' => time()
            ];
        }

        GoodsContent::query()->insert($contentData);

        // 微信默认配置
        $conf = [];
        $conf['cp_id'] = $params['cp_id'];
        $conf['appid'] = env('APP_ID');
        $conf['appsecret'] = env('APP_SECRET');
        $conf['token'] = 'test123';
        $conf['encodingaeskey'] = '5b638eb6cdaca2a1c80b86982218251c12345678901';
        $conf['welcomemsg'] = '欢迎使用珠小宝~';

        WxaccountSetting::query()->create($conf);

        //微信推送消息配置
        $temp = [];
        $temp['cp_id'] = $params['cp_id'];
        $temp['birthday'] = '';
        $temp['score'] = '8eR0HFNAUUMZCkku_M6DJXfJANmLvRbtLK-cB1k-tmg';
        $temp['recharge_order'] = '8eR0HFNAUUMZCkku_M6DJXfJANmLvRbtLK-cB1k-tmg';
        $temp['deposit_order'] = '8eR0HFNAUUMZCkku_M6DJXfJANmLvRbtLK-cB1k-tmg';
        $temp['recovery_order'] = 'PYoqYhUC6LESZIltaTp3UEZpMS6R-UZWlWnsSfrM-fI';
        $temp['sales_order'] = 'BWdCu7rNB9TwIdAPwf8PmOpN8tnoVTOP4JG5Og_9t9U';

        WxaccountTemplate::query()->create($temp);

        return true;
    }
}
